package com.arch.dev.server;

import java.io.File;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.arch.dev.client.GreetingService;
import com.arch.dev.client.vo.BudgetVO;
import com.arch.dev.client.vo.PdfVO;
import com.arch.dev.server.report.PdfJasperReport;
import com.arch.dev.server.report.ReportFactory;

@Service
public class JobService {
	
	Logger logger = Logger.getLogger(JobService.class);
	
	ReportFactory pdfJasperReport = new PdfJasperReport();
	
	@Autowired ServletContext servletContext = null; 
	
	@Autowired
	GreetingService greetingServiceImpl;
	
	/*@Scheduled(cron="0 1-59 1-23 * * ?")*/
	public void processPDFJob(){
		logger.info("********Starting job*********");		
		try {
			logger.info("********Getting  data*********");	
			List<BudgetVO>  budgetVO = greetingServiceImpl.getAllValues();
			logger.info("********Generating PDF*********");	
			generatePDFJob(budgetVO);
			logger.info("********Sent Email*********");	
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		logger.info("********Completed job********");
	}

	private void emailPDF(String fileName, String filePath){	
		Map<String,String> attachmentMap = new HashMap<String,String>();
		attachmentMap.put(fileName+".pdf", filePath);
		EmailServiceImpl.getInstance().sendEmailWithAttachment("Report", "Monthly Report", attachmentMap);

	}
	
	public void generatePDFJob(List<BudgetVO> budgetVOs) throws Exception {

		Calendar cl = Calendar.getInstance();

		Date date = cl.getTime();

		Long time = cl.getTimeInMillis();

		String pdfName = "MONTHLY_PDF_" + time;

		ServletContext sc = servletContext;

		logger.info("*********" + sc.getRealPath("/"));

		File directory = new File(sc.getRealPath("/") + "PDF");

		if (!directory.exists()) {

			directory.mkdir();

		}

		File file = new File(directory, pdfName + ".pdf");

		logger.info("*****" + file.getAbsolutePath());

		Collections.sort(budgetVOs, new Comparator <BudgetVO>(){

			@Override
			public int compare(BudgetVO o1, BudgetVO o2) {
				// TODO Auto-generated method stub
				return o1.getDate().compareTo(o2.getDate());
			}
			
		});
		
		// firstPDF.generatePDF(file, absoluteDiskPath, budgetVOs);

		pdfJasperReport.getReport(budgetVOs, file.getAbsolutePath(),
				sc.getRealPath("/"));

		PdfVO pdfVO = new PdfVO();

		pdfVO.setDate(date);

		pdfVO.setName(pdfName);		
		
		greetingServiceImpl.savePDF(pdfVO);
		
		emailPDF(pdfName, file.getAbsolutePath());

	}
	
}
